package com.btl.component.crypto.aes.advice;

import com.btl.boot.core.dto.response.R;
import com.btl.component.crypto.aes.SecurityCrypt;
import com.btl.component.crypto.aes.annotation.Encrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, @NonNull Class converterType) {
        return returnType.hasMethodAnnotation(Encrypt.class)
                && R.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public Object beforeBodyWrite(Object body, @NonNull MethodParameter returnType, @NonNull MediaType mediaType, @NonNull Class converterType, @NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response) {
        if (body instanceof R<?> r && r.getData() != null && r.getCode() == 0) {
            Object encrypt = SecurityCrypt.encrypt(r.getData());
            return R.ok(encrypt);
        }
        return body;
    }
}
